<?php

namespace Frieza\Modules\Tpwd\Controllers;

use App\Http\Controllers\Controller;
use Biz\pockets\excel\DownExcel;
use Biz\tools\Mail;
use Biz\tools\TbkUnion;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;
    const SHORT_PREFIX = 'http://l.hhz1.cn/';

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function create(Request $request, Content $content)
    {
        $adminEmail = Admin::user()->email;
        $form = new Form([]);
        $form->html('<span style="color: red">建议！使用阿里妈妈官方转链工具，已支持批量转链功能，且转链结果支持excel下载。支持能力更强，返回信息更丰富！</span>');
        $form->html('<img src="https://img.alicdn.com/imgextra/i2/6000000003677/O1CN01Od8Q331d27736jNGT_!!6000000003677-2-QNBIZ.png" style="width: 941px;height: 321px">', '建议使用官方工具');
        $form->text('email', '邮箱')->default($adminEmail)->help('请输入你的邮箱，生成链接将以邮件的方式发送给你。')->required();
        $form->textarea('url', '淘宝链接')->rows(20)->help('一行一个，淘宝链接。生成的淘口令和淘链接会发送邮件附件。')->required();
        $form->radio('adzone_id', '推广位')->options(TbkUnion::ADZONE_TEXT_MAP)->default(TbkUnion::ADZONE_ID)->required();
        $form->text("relation_id", "渠道关系ID")->help('非必传，如果需要则填');
        $form->action('/admin/tpwd/save');
        return $content->header('淘口令&淘客链接生成工具')->breadcrumb(
            ['text' => '淘口令&淘客链接生成工具'])->body($form->render());
    }

    public function save(Request $request, Content $content)
    {
        $params = $request->all();
        $email = $params['email'];
        try {
            $urls = $params['url'];
            $relationID = $params['relation_id'];
            $arr = explode("\r\n", $urls);
            $list = [];
            $adZoneId = $params['adzone_id'];
            foreach ($arr as $url) {
                list($tpwd, $itemID, $tbkUrl, $couponUrl) = $this->getTpwd($url, $adZoneId, $relationID);
                $list[] = [
                    'url' => $url,
                    'tpwd' => $tpwd,
                    'tbk_url' => $tbkUrl,
                    'coupon_url' => $couponUrl,
                    'item_id' => $itemID,
                    'relation_id' => $relationID,
                ];
            }
            if ($list) {
                $this->admExportTpwd($list, $adZoneId, $email);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return back()->with(compact('success'));

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput(compact('error'));
        }
    }

    private function getTpwd($url, $adZoneId, $relationID = "")
    {
        $itemId = TbkUnion::getItemIdByUrl($url);
        // 淘口令
        $tpwd = '';
        // 商品淘客链接
        $tbkUrl = '';
        // 商品优惠券推广链接
        $couponUrl = "";
        if ($itemId) {
            $res = TbkUnion::tbkCouponConvert($itemId, $adZoneId, $relationID);
            $tbkUrl = $res['item_url'] ?? '';
            $couponUrl = $res['coupon_click_url'] ?? '';
            $tpwd = TbkUnion::tbkTpwdCreate($tbkUrl)['model'] ?? '';
        }
        return [$tpwd, $itemId, $tbkUrl, $couponUrl];
    }

    private function admExportTpwd($arr, $adZoneId, $adminEmail)
    {
        $adZoneDesc = TbkUnion::ADZONE_TEXT_MAP[$adZoneId];
        $header = ['链接地址', '淘口令', '商品淘客链接', '商品优惠券推广链接', '商品ID', '渠道关系ID'];
        $letter = range('A', 'F');
        $excelObj = new DownExcel();
        $excelObj->saveType = 1;
        $excelObj->setFileName('淘口令列表-' . $adZoneDesc);
        $excelObj->setSheetTitle('淘口令列表-' . $adZoneDesc);
        //设置列宽
        $widths = ['A' => 100, 'B' => 50, 'C' => 100, 'D' => 100, 'E' => 50, 'F' => 50];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        $excelObj->setTextFormat('C');
        $excelObj->setTextFormat('D');
        $excelObj->setTextFormat('E');
        $excelObj->setTextFormat('F');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $fileName = $excelObj->create($arr, $header);
        Mail::send($adminEmail, '淘口令列表-' . $adZoneDesc, '淘口令列表-' . $adZoneDesc, $fileName);
    }


}